package com.xincheng.shuimalong.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.view.CameraTopRectView;
import com.xincheng.shuimalong.common.Constant;

public class IdCardCameraActivity extends Activity implements SurfaceHolder.Callback, OnClickListener {

    private SurfaceView mySurfaceView = null;
    private SurfaceHolder mySurfaceHolder = null;
    private CameraTopRectView topView = null; //自定义顶层view

    private Camera myCamera = null;
    private Camera.Parameters myParameters;

    private TextView takeTxt;
    private TextView cancelTxt;

    private boolean isPreviewing = false;
    private Bitmap bm;
    private static final String IMG_PATH = Constant.ID_CARD_PATH;
    private File file;
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        Window myWindow = this.getWindow();
        myWindow.setFlags(flag, flag);
        setContentView(R.layout.idcard_camera_layout);
        mySurfaceView = (SurfaceView) findViewById(R.id.sv_camera);
        mySurfaceView.setZOrderOnTop(false);
        mySurfaceHolder = mySurfaceView.getHolder();
        mySurfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
        mySurfaceHolder.addCallback(this);
        mySurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        topView = (CameraTopRectView) findViewById(R.id.top_view);
        int from = getIntent().getExtras().getInt(IntentKey.FROM, 0);
        XLog.e("from=>" + from);
        switch (from) {
            case 1:
                topView.setTips("请将身份证放入到框中");
                break;
            case 2:
                topView.setTips("请将行驶证放入到框中");
                break;
        }
        takeTxt = (TextView) findViewById(R.id.txt_take);
        cancelTxt = (TextView) findViewById(R.id.txt_cancel);
        takeTxt.setClickable(false);
        cancelTxt.setClickable(false);
        takeTxt.setOnClickListener(this);
        cancelTxt.setOnClickListener(this);
//        topView.onDraw(new Canvas());
        initCamera();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (myCamera == null) {
            initCamera();
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if (myCamera != null) {
            isPreviewing = false;
            takeTxt.setClickable(false);
            cancelTxt.setClickable(false);
            myCamera.release(); // release the camera for other applications
            myCamera = null;
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (myCamera != null) {
            myCamera.release();
            myCamera = null;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        try {
            if (myCamera == null) {
                return;
            }
            myCamera.setPreviewDisplay(mySurfaceHolder);
            myCamera.startPreview();
            isPreviewing = true;
            takeTxt.setClickable(true);
            cancelTxt.setClickable(true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        if (myCamera != null) {
            myCamera.stopPreview();
            myCamera.release();
            myCamera = null;
        }

    }

    ShutterCallback myShutterCallback = new ShutterCallback() {

        public void onShutter() {
            // TODO Auto-generated method stub

        }
    };
    PictureCallback myRawCallback = new PictureCallback() {

        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub

        }
    };
    PictureCallback myjpegCalback = new PictureCallback() {

        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub
            if (data != null) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
                        data.length);
                XLog.e(bitmap.getWidth() + "," + bitmap.getHeight());
                isPreviewing = false;
                takeTxt.setText("确定");
                Bitmap sizeBitmap = Bitmap.createScaledBitmap(bitmap, topView.getViewWidth(), topView.getViewHeight()
                        , true);
                XLog.e(sizeBitmap.getWidth() + "," + sizeBitmap.getHeight());
                XLog.e(topView.getRectLeft() + "," + topView.getRectTop());
                XLog.e((topView.getRectRight() - topView.getRectLeft()) + "," +
                        (topView.getRectBottom() - topView.getRectTop()));
                int top = topView.getRectTop() - CommonUtil.getStatusBarHeight(IdCardCameraActivity.this);
                bm = Bitmap.createBitmap(sizeBitmap, topView.getRectLeft(), top,
                        topView.getRectRight() - topView.getRectLeft(), topView.getRectBottom() - topView.getRectTop());
                // 截取
            }
        }
    };

    // 初始化摄像头
    public void initCamera() {
        if (myCamera == null) {
            myCamera = getCameraInstance();
        }
        if (myCamera != null) {
            myParameters = myCamera.getParameters();
            myParameters.setPictureFormat(PixelFormat.JPEG);
            myParameters.set("rotation", 90);
            if (getCameraFocusable() != null) {
                myParameters.setFocusMode(getCameraFocusable());
            }
            int width = myParameters.getSupportedPreviewSizes().get(0).width;
            int hidth = myParameters.getSupportedPreviewSizes().get(0).height;
            myParameters.setPreviewSize(width, hidth);
            myParameters.setPictureSize(width, hidth); // 1280, 720

            myCamera.setDisplayOrientation(90);
            myCamera.setParameters(myParameters);
        } else {
            Toast.makeText(this, "相机错误！", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        if (v.getId() == R.id.txt_take) {

        }
        switch (v.getId()) {
            case R.id.txt_take:
                if (isPreviewing) {
                    // 拍照
                    try {
                        myCamera.takePicture(myShutterCallback, myRawCallback,
                                myjpegCalback);
                    } catch (Exception e) {
                        CommonUtil.showToast(this,"拍照失败！");
                    }
                } else {
                    // 保存图片
                    File file = MyUtil.getOutputMediaFile(this, IMG_PATH, "idcard_");
                    this.file = file;
                    if (file != null && bm != null) {
                        FileOutputStream fout;
                        try {
                            fout = new FileOutputStream(file);
                            BufferedOutputStream bos = new BufferedOutputStream(fout);
                            // Bitmap mBitmap = Bitmap.createScaledBitmap(bm,
                            // topView.getViewWidth(), topView.getViewHeight(),
                            // false);
                            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                            bos.flush();
                            bos.close();
                            this.uri = Uri.fromFile(file);
                            Intent intent = new Intent();
                            intent.setData(uri);
                            Bundle bundle = new Bundle();
                            intent.putExtras(bundle);
                            setResult(Constant.CAMERA_SUCESS, intent);
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(getBaseContext(), "获取文件失败", Toast.LENGTH_SHORT).show();
                    }
                    finish();
                }
                break;
            case R.id.txt_cancel:
                if (isPreviewing) {
                    finish();
                    // 退出相机
                } else {
                    if (myCamera == null) {
                        initCamera();
                    }
                    // 重新拍照
                    try {
                        myCamera.setPreviewDisplay(mySurfaceHolder);
                        myCamera.startPreview();
                        isPreviewing = true;
                        takeTxt.setText("拍照");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }

    }

    private String getCameraFocusable() {
        List<String> focusModes = myParameters.getSupportedFocusModes();
        if (focusModes
                .contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
            return Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE;
        } else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            return Camera.Parameters.FOCUS_MODE_AUTO;
        }
        return null;
    }

    /**
     * A safe way to get an instance of the Camera object.
     */
    public Camera getCameraInstance() {
        Camera c = null;
        try {
            if (getCameraId() >= 0) {
                c = Camera.open(getCameraId()); // attempt to get a Camera
                // instance
            } else {
                return null;
            }
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            Log.e("getCameraInstance", e.toString());
        }
        return c; // returns null if camera is unavailable
    }

    private int getCameraId() {
        if (!checkCameraHardware(this)) {
            return -1;
        }
        int cNum = Camera.getNumberOfCameras();
        int defaultCameraId = -1;
        CameraInfo cameraInfo = new CameraInfo();
        for (int i = 0; i < cNum; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                defaultCameraId = i;
            }
        }
        return defaultCameraId;
    }

    /**
     * Check if this device has a camera
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

}